package com.handinfo.android.core.resource;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Xml;

import com.handinfo.android.DWGameManager;
import com.handinfo.android.utils.Tools;

public class IORWFile
{
//	public static String mResSDDir = "mnt/sdcard/xianyuanonline/res";
//	public static String mResDATADir = "data/data/com.handinfo.android/files/res";
//	File dirAnim = new File(mResSDDir + DWSerializableFactory.DIR_ANIM);
//	public static final byte RESOURCE_TYPE_PNG = 1;
//	public static final byte RESOURCE_TYPE_ANIM = 2;
//	public static final byte RESOURCE_TYPE_BG = 3;
//	public static final byte RESOURCE_TYPE_ACTOR = 4;
//	public static final byte RESOURCE_TYPE_ROLE = 5;
//	public static final byte RESOURCE_TYPE_NPC = 6;
//	public static final byte RESOURCE_TYPE_ITEM = 7;
//	public static final byte RESOURCE_TYPE_SCENE = 8;
//	public static final byte RESOURCE_TYPE_SOUND = 9;

//	public void writeResource(ResHead head, byte[] dis)
//	{
//		try {
//			SharedPreferences resdirectory = DWGameManager.getInstance().handinfoShared;
//			int whileKeep = resdirectory.getInt(sharedxmlResWhileKeep, 0);
//			String folderNameSD = null;
//			switch (head.m_type) {
//				case DWSerializableFactory.RESOURCE_TYPE_ANIM:
//					folderNameSD = DWSerializableFactory.DIR_ANIM;
//					break;
//				case DWSerializableFactory.RESOURCE_TYPE_BG:
//					folderNameSD = DWSerializableFactory.DIR_BG;
//					break;
//				case DWSerializableFactory.RESOURCE_TYPE_PNG:
//					folderNameSD = DWSerializableFactory.DIR_IMG;
//					break;
//				case DWSerializableFactory.RESOURCE_TYPE_SCENE:
//					folderNameSD = DWSerializableFactory.DIR_SCENE;
//					break;
//				case DWSerializableFactory.RESOURCE_TYPE_SOUND:
//					folderNameSD = DWSerializableFactory.DIR_SOUND;
//					break;
//			}
//			if (whileKeep == 1) {
//				writeFile(head.m_url, mResDATADir + folderNameSD, dis);
//			}
//			else {
//				writeSDCardFile(mResSDDir + folderNameSD + head.m_url, dis);
//			}
//			ResourceVerifier.resAll.put(head.m_url, head);
//		}
//		catch (Exception e) {
//			Tools.debug(e);
//		}
//	}

	public byte[] readResource(ResHead head)
	{
		byte[] data = readSDCardFile(DWGameManager.s_res_dir + File.separator + head.m_url);
		return data;
	}

//	private void createDir()
//	{
//		File filedir = new File(mResSDDir);
//		if (!filedir.exists()) {
//			filedir.mkdir();
//		}
//		File dirAnim = new File(mResSDDir + DWSerializableFactory.DIR_ANIM);
//		if (!dirAnim.exists()) {
//			dirAnim.mkdir();
//		}
//		File dirImg = new File(mResSDDir + DWSerializableFactory.DIR_IMG);
//		if (!dirImg.exists()) {
//			dirImg.mkdir();
//		}
//		File dirbg = new File(mResSDDir + DWSerializableFactory.DIR_BG);
//		if (!dirbg.exists()) {
//			dirbg.mkdir();
//		}
//		// File sdDir = getSDCardDir();
//		// File fileDir = new File(sdDir, "hindinfo");
//		// if (!fileDir.exists()) {
//		// fileDir.mkdir();
//		// }
//	}

//	// 往sd卡中写入文件
//	public void writeSDCardFile(String path, byte[] buffer) throws IOException
//	{
//		createDir();
//		File file = new File(path);
//		if (!file.exists()) {
//			file.createNewFile();
//		}
//		FileOutputStream fos = new FileOutputStream(file);
//		fos.write(buffer);// 写入buffer数组。如果想写入一些简单的字符，可以将String.getBytes()再写入文件;
//		fos.flush();
//		fos.close();
//	}
//
	// 读取sd中的文件
	public byte[] readSDCardFile(String path)
	{
		byte buffer[] = null;
		try {
			File file = new File(path);
			FileInputStream fis;
			fis = new FileInputStream(file);
			int buffersize = fis.available();// 取得输入流的字节长度
			buffer = new byte[buffersize];
			fis.read(buffer);// 将数据读入数组
			fis.close();// 读取完毕后要关闭流。
		}
		catch (FileNotFoundException e) {
			Tools.debugPrintln("没要找到资源 ：  " + path);
			Tools.debug(e);
		}
		catch (Exception e) {
			Tools.debugPrintln("资源数据文件读取异常： " + path);
			Tools.debug(e);
		}
		return buffer;
	}

	/**
	 * 获取sdcard
	 * 
	 * @return
	 */
	public static File getSDCardDir()
	{
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File sdCardDir = Environment.getExternalStorageDirectory();
			return sdCardDir;
		}
		else {
			return null;
		}
	}

//	// ///////往data/data里存写数据
//	public static void writeFile(String fileNam, String folderName, byte[] dis)
//	{
//		try {
////			File filedir1 = new File(folderName);
////			if (!filedir1.exists()) {
////				filedir1.mkdir();
////			}
//			File m_filedir = new File(folderName);
//			if (!m_filedir.exists()) {
//				m_filedir.mkdirs();
//			}
////			File fe = DWGameManager.getInstance().getCurrentActivity()
////					.getContext().getDir(folderName, Context.MODE_WORLD_WRITEABLE);
//			FileOutputStream outStream = new FileOutputStream(m_filedir + fileNam);
//
//			outStream.write(dis);
//			outStream.close();
//		}
//		catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
//
	public static byte[] readFile(String fileNam)
	{
		try {
			// FileInputStream inputStream =
			// DWGameManager.getInstance().getCurrentActivity().getContext().openFileInput(fileNam);
			File file = new File(fileNam);
			FileInputStream inputStream = new FileInputStream(file);
			// Log.i("FileTest", readInStream(inStream));

			ByteArrayOutputStream os = new ByteArrayOutputStream();
			int b = -1;
			while ((b = inputStream.read()) != -1) {
				os.write(b);
			}
			byte bytearr[] = os.toByteArray();
			os.close();
			inputStream.close();
			return bytearr;
		}
		catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

//	// xml 解析 相关
//
//	public static void getXml()
//	{
//		if (ResourceVerifier.resAll == null) {
//			ResourceVerifier.resAll = new HashMap<String, ResHead>();
//		}
//		Map names = ResourceVerifier.resAll;// 初始化集合;
//		File newxmlfile = DWGameManager.getInstance().getCurrentActivity()
//				.getContext().getDir("xml", Context.MODE_WORLD_WRITEABLE);
//		if (!newxmlfile.exists()) {
//			Tools.debugPrintln("xml解析", "sharedxml解析错误。。。。。");
//			return;
//		}
//		FileInputStream inputStream;
//		ResHead res = null;
//		try {
//			inputStream = new FileInputStream(newxmlfile + RESsharedxmlName);
//			// 获取一个XmlPullParser   
//			XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory.newInstance();
//			XmlPullParser parser = xmlPullParserFactory.newPullParser();
//			parser.setInput(inputStream, "UTF-8");
//			int event = parser.getEventType();// 产生第一个事件
//			while (event != XmlPullParser.END_DOCUMENT) {
//				String nodeName = parser.getName();
//				switch (event) {
//					case XmlPullParser.START_TAG:// 判断当前事件是否是标签元素开始事件
//						if (xmlres.equals(nodeName)) {
//							res = new ResHead();
//							break;
//						}
//						if (res != null) {
//							if (xmlresname.equals(nodeName)) {// 判断开始标签元素是否是
//								res.m_url = parser.nextText();
//							}
//							else if (xmlrestype.equals(nodeName)) {
//								res.m_type = Byte.parseByte(parser.nextText());
//							}
//						}
//						break;
//					case XmlPullParser.END_TAG:// 判断当前事件是否是标签元素结束事件
//						if (xmlres.equals(parser.getName())) {// 判断结束标签元素是否是
//							names.put(res.m_url, res);// 将//添加到集合
//							res = null;
//						}
//						else if (xmlstart.equals(parser.getName())) {
//							return;
//						}
//						break;
//				}
//				event = parser.nextTag();
//			}// end while
//		}
//		catch (Exception e) {
//			Tools.debug(e);
//		}
//	}

	/**
	 * 创建xml 文件
	 * 
	 * @param resName
	 */
//	public static void XmlFileCreator(Map<String, ResHead> resHands)
//	{
//		File newxmlfile = DWGameManager.getInstance().getCurrentActivity()
//				.getContext().getDir("xml", Context.MODE_WORLD_WRITEABLE);
//		Tools.debugPrintln("xml路径路径路径：" + newxmlfile + "/resNames.xml");
//		try {
//			if (!newxmlfile.exists())
//				newxmlfile.createNewFile();
//		}
//		catch (IOException e) {
//			Tools.debugPrintln("IOException", "exception in createNewFile() method");
//		}
////		String newxmlfile="mnt/sdcard/datangonling/res";
//		// we have to bind the new file with a FileOutputStream
//		FileOutputStream fileos = null;
//		try {
//			fileos = new FileOutputStream(newxmlfile + "/resNames.xml");
//		}
//		catch (FileNotFoundException e) {
//			Tools.debugPrintln("FileNotFoundException",
//					"can't create FileOutputStream");
//		}
//		// we create a XmlSerializer in order to write xml data
//		XmlSerializer serializer = Xml.newSerializer();
//		try {
//			// we set the FileOutputStream as output for the serializer, using
//			// UTF-8 encoding
//			serializer.setOutput(fileos, "UTF-8");
//			// Write <?xml declaration with encoding (if encoding not null) and
//			// standalone flag (if standalone not null)
//			serializer.startDocument(null, Boolean.valueOf(true));
//			// set indentation option
//			serializer.setFeature(
//					"http://xmlpull.org/v1/doc/features.html#indent-output",
//					true);
//			// start a tag called "root"
//			Set<String> set = resHands.keySet();
//			serializer.startTag(null, xmlstart);
//			for (String s : set) {
//				serializer.startTag(null, xmlres);
//				serializer.startTag(null, xmlresname);
//				serializer.text(resHands.get(s).m_url);
//				serializer.endTag(null, xmlresname);
//				serializer.startTag(null, xmlrestype);
//				serializer.text(resHands.get(s).m_type + "");
//				serializer.endTag(null, xmlrestype);
//				serializer.endTag(null, xmlres);
//			}
//			serializer.endTag(null, xmlstart);
//			serializer.endDocument();
//			// write xml data into the FileOutputStream
//			serializer.flush();
//			// finally we close the file stream
//			fileos.close();
//		}
//		catch (Exception e) {
//			Tools.debugPrintln("Exception",
//					"error occurred while creating xml file");
//		}
//	}
//
//	/**
//	 * 检查是否缺失资源
//	 * 
//	 * @return
//	 */
//	public static Map isMissRes(Map<String, ResHead> resHeads)
//	{
//		Map allresList = ResourceVerifier.resAll;
//		Map resMiss = new HashMap<String, ResHead>();
//		SharedPreferences resdirectory = DWGameManager.getInstance().handinfoShared;
//		Set<String> set = resHeads.keySet();
//		for (String s : set) {
//
//			String folder = null;
//			switch (resHeads.get(s).m_type) {
//				case DWSerializableFactory.RESOURCE_TYPE_ANIM:
//					folder = DWSerializableFactory.DIR_ANIM;
//					break;
//				case DWSerializableFactory.RESOURCE_TYPE_PNG:
//					folder = DWSerializableFactory.DIR_IMG;
//					break;
//				case DWSerializableFactory.RESOURCE_TYPE_BG:
//					folder = DWSerializableFactory.DIR_BG;
//					break;
//				case DWSerializableFactory.RESOURCE_TYPE_SCENE:
//					folder=DWSerializableFactory.DIR_SCENE;
//					break;
//				case DWSerializableFactory.RESOURCE_TYPE_SOUND:
//					folder=DWSerializableFactory.DIR_SOUND;
//					break;
//			}
//			int whileKeep = resdirectory.getInt(sharedxmlResWhileKeep, 0);
//			String pathName = null;
//			if (whileKeep == 0) { // sd卡
//				pathName = mResSDDir + folder + resHeads.get(s).m_url;
//				if (!fileIsExist(pathName)) {
//					resMiss.put(resHeads.get(s).m_url, resHeads.get(s));
//				}
//			}
//			else if (whileKeep == 1) {// 内存
//
//				pathName = mResDATADir + folder + resHeads.get(s).m_url;
//				if (!fileIsExist(pathName)) {
//					resMiss.put(resHeads.get(s).m_url, resHeads.get(s));
//				}
//			}
//		}
//		return resMiss;
//
//	}

	/**
	 * 文件是否存在
	 * 
	 * @param pathname
	 * @return
	 */
	public static boolean fileIsExist(String pathname)
	{
		if (new File(pathname).exists()) {
			return true;
		}
		else {
			return false;
		}

	}

	/**
	 * 解压zip格式的压缩包
	 * 
	 * @param filePath
	 * 压缩文件路径
	 * @param outPath
	 * 输出路径
	 * @return 解压成功或失败标志
	 * @throws IOException
	 */
	public static Boolean unZip(String filePath, String outPath) throws IOException
	{
//		InputStream unzipfile = DWGameManager.getInstance().getCurrentActivity().getResources()
//				.getAssets().open("res/"+filePath);
		try {
			FileInputStream unzipfile = new FileInputStream(filePath);
			// 解压缩的文件名
			ZipInputStream zin = new ZipInputStream(unzipfile);
			ZipEntry entry;
			// 创建文件夹
			while ((entry = zin.getNextEntry()) != null) {
				if (entry.isDirectory()) {
					File directory = new File(outPath, entry.getName());
					if (!directory.exists()) {
						if (!directory.mkdirs()) {
//							System.exit(0);
						}
					}
					zin.closeEntry();
				}
				else {
					File myFile = new File(outPath, entry.getName());
					if (!myFile.exists()) {
						myFile.createNewFile();
					}

					FileOutputStream fout = new FileOutputStream(myFile);
					DataOutputStream dout = new DataOutputStream(fout);
					byte[] b = new byte[1024];
					int len = 0;
					while ((len = zin.read(b)) != -1) {
						dout.write(b, 0, len);
					}
					dout.close();
					fout.close();
					zin.closeEntry();
				}
			}

			return true;
		}
		catch (Exception e) {
			Tools.debug(e);
			return false;
		}
	}

	/**
	 * 判断是wifi还是3g网络，wifi就可以建议下载或者.....。
	 * @param context
	 * @return
	 */
	public static boolean isWifi(Context context)
	{
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkINfo = cm.getActiveNetworkInfo();
		if (networkINfo != null && networkINfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}
		return false;
	}
//	public static String xmlstart = "resource";
//	public static String xmlres = "res";
//	public static String xmlresname = "resname";
//	public static String xmlrestype = "restype";
//	public static String RESsharedxmlName = "/resNames.xml"; //
//
//	public static final String sharedxmlName = "handinfo"; //
//	
//	
//	public static String sharedxmlResWhileKeep = "resDirectory"; // 0 ：SD卡 1：内存
//
//
//	public static String currentVresions = "versions"; //本地资源版本号

}
